package models

import (
	"errors"
	"fmt"
	"time"

	"coinsend/utils"

	"github.com/astaxie/beego/orm"
)

type User struct {
	Id       int
	Type     int
	Username string
	Password string
	Remarks  string
	Status   int
	Created  int
}

func init() {

	orm.RegisterModel(new(User))
}

//检查用户
func CheckUser(username, password string) (int, Response) {
	var wltuser User
	var error Response

	o1 := orm.NewOrm()
	o1.QueryTable("User").Filter("Username", username).One(&wltuser)
	//fmt.Println(wltuser.Password, utils.GetMD5(password))
	if wltuser.Id == 0 {
		error.Code = 1
		error.Msg = "用户不存在"
	} else if wltuser.Status == 20 {
		error.Code = 1
		error.Msg = "用户被禁用"
	} else if wltuser.Password == utils.GetMD5(password) {

		return wltuser.Id, error
	} else {
		error.Code = 1
		error.Msg = "密码错误"
	}

	return wltuser.Id, error
}

//添加用户
func ORMAddUser(username, password, Remarks string) (int, error) {
	var wltuser User

	o := orm.NewOrm()
	o.QueryTable("User").Filter("Username", username).One(&wltuser)
	if wltuser.Id != 0 {
		return 0, errors.New("用户名已存在,请替换用户名")
	}
	user := new(User)
	user.Username = username
	user.Password = utils.GetMD5(password)
	user.Status = 10
	user.Remarks = Remarks
	user.Type = 1
	user.Created = int(time.Now().Unix())
	id, err := o.Insert(user)
	return int(id), err

}

//获取用户列表
func ORMListUser() ([]User, error) {
	var wltuser []User
	var user []User
	o := orm.NewOrm()
	o.QueryTable("User").All(&wltuser)
	for _, v := range wltuser {

		v.Password = ""
		user = append(user, v)

	}
	return user, nil

}

//获取用户信息
func ORMGetUserById(uid int) (*User, error) {
	o := orm.NewOrm()
	user := new(User)
	user.Id = int(uid)
	o.Read(user)
	if user.Username == "" {
		return user, errors.New("账号不存在")
	}
	user.Password = ""
	return user, nil
}

//删除用户
func ORMDelUser(uid int64) (int64, error) {
	if uid == 1 {
		return 0, errors.New("管理员账号不可删除")
	}
	o := orm.NewOrm()
	user := new(User)
	user.Id = int(uid)
	fmt.Println(o.Delete(user))
	return o.Delete(user)

}

//修改/禁用用户
func ORMUpdateUser(uid int64, password, Remarks string, Status int) (int64, error) {
	if uid == 1 && Status == 20 {
		return 0, errors.New("管理员账号不可禁用")
	}
	o := orm.NewOrm()
	user := new(User)
	user.Id = int(uid)
	o.Read(user)
	if user.Username == "" {
		return 0, errors.New("账号不存在")
	}
	if password != "" {
		user.Password = utils.GetMD5(password)
	}
	if Remarks != "" {
		user.Remarks = Remarks
	}

	user.Status = Status

	return o.Update(user)

}

//修改密码
func ORMUpdateUserPassword(uid int64, passwordold, password string) (int64, error) {

	o := orm.NewOrm()
	user := new(User)
	user.Id = int(uid)
	o.Read(user)
	if user.Username == "" {
		return 0, errors.New("账号不存在")
	}

	if user.Password == utils.GetMD5(passwordold) {
		user.Password = utils.GetMD5(password)
	} else {
		return 0, errors.New("原始密码错误")
	}

	return o.Update(user)

}
